package com.kbt.base;

import android.app.*;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Environment;

import cn.jpush.android.api.JPushInterface;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.Volley;
import com.kbt.activity.LoginActivity;
import com.kbt.activity.R;
import com.kbt.activity.StoreActivity;
import com.kbt.commont.Constants;
import com.kbt.model.data.GoodForCarInfo;
import com.kbt.model.data.ShopCarBean;
import com.kbt.util.utils.ScreenManager;
import com.kbt.util.utils.SharePreferenceUtils;
import com.kbt.util.utils.UnCeHandler;
import com.nostra13.universalimageloader.cache.disc.impl.UnlimitedDiscCache;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.WeakMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;
import com.nostra13.universalimageloader.utils.StorageUtils;
import com.thinkland.sdk.android.JuheSDKInitializer;

import java.io.File;
import java.util.ArrayList;
import java.util.List;


public class BaseApplication extends Application {

    ArrayList<Activity> list = new ArrayList<Activity>();
    ArrayList<Activity> listtwo = new ArrayList<Activity>();
    //checkbox选中的的position
    public List<Integer> ischeck = new ArrayList<Integer>();
    //购物车选择的商品件数
    public int shopCarNumber = 0;
    //购物车的商品总价
    public double shopCarTotal=0;
    //购物车商品应付总价
    public double shopCarPayable=0;
    //运费
    public double freight=0;
    //优惠
    public double discount=0;

    //底部按钮item
    public Integer currentItem=null;
    //购物车的状态
    public String carStatus=null;

    public Activity activity;

    public SharePreferenceUtils share;

    //购物车商品数量
    public int shopType=0;
    //情况说明
    public String qingKuang="";

    //申请售后售后类型
    public String apply_type="1";
    //是否更新
    public static boolean isUpdate = true;



    private static final String TAG = BaseApplication.class.getName();

    /**
     * 单例 *
     */
    private static BaseApplication mBaseApplication;

    /**
     * 管理所有的activity *
     */
    public ScreenManager mScreenManager = null;

    /**
     * 单例 Context *
     */
    private Context context;

    /**
     * 全局定义的RequestQueue *
     */
    private static RequestQueue mRequestQueue;
    //微信支付是否失败
    public static boolean isWeixin=false;
    //确认支付商品列表
    public static List<ShopCarBean> shopCarBeans =new ArrayList<ShopCarBean>();

    /**
     * Vollery 管理器 单例
     *
     * @return
     */
    public static RequestQueue getRequestQueuemanager() {
        if (mRequestQueue == null) {
            mRequestQueue = Volley.newRequestQueue(mBaseApplication);
        }
        return mRequestQueue;
    }

    /**
     * 单例的BaseApplication
     *
     * @return
     */
    public static BaseApplication getInstance() {
        if (mBaseApplication == null) {
            mBaseApplication = new BaseApplication();
        }
        return mBaseApplication;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        mBaseApplication = this;
        context = this;
        mScreenManager = ScreenManager.getScreenManager();
        share = new SharePreferenceUtils(BaseApplication.this);
        start();
        init();
        JPushInterface.init(this);
        JuheSDKInitializer.initialize(getApplicationContext());
    }
    //判断是否登录
    public boolean isLogin(){
        if(share.getString("user_mobile","").equals("")){
           return false;
        }
        return true;
    }

    /**
     * 初始化信息
     */
    public void start() {

        // 文件路径设置
        String parentPath = null;

        // 存在SDCARD的时候，路径设置到SDCARD
        if (Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) {
            parentPath =
                    Environment.getExternalStorageDirectory().getPath()
                            + File.separatorChar + getPackageName();
            // 不存在SDCARD的时候
        } else {
            parentPath =
                    Environment.getDataDirectory().getPath()
                            + File.separatorChar + "data" + File.separatorChar + getPackageName();
        }

        // 路径设置
        Constants.rootPath = parentPath;
        Constants.imgPath = parentPath + "/imagecache/";
        Constants.bugPath = parentPath + "/bugfile/";
        // 创建目录
        new File(Constants.imgPath).mkdirs();
        new File(Constants.bugPath).mkdirs();

        // 图片加载和缓存路径
        initImageLoader();
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();

        // 清除缓存和內存
        ImageLoader imageLoader = ImageLoader.getInstance();
        imageLoader.clearMemoryCache();
        imageLoader.clearDiscCache();
    }

    public void initImageLoader() {
        // 获取应用程序最大可用内存
        int maxMemory = (int) Runtime.getRuntime().maxMemory();
        int cacheSize = maxMemory / 8;

        // 缓存路径,第二个参数
        File cacheDir =
                StorageUtils.getOwnCacheDirectory(mBaseApplication, Constants.imgLoaderPath);

        DisplayImageOptions options =
                new DisplayImageOptions.Builder().cacheInMemory(true).cacheOnDisc(true)
                        .imageScaleType(ImageScaleType.IN_SAMPLE_INT)
                        .bitmapConfig(Bitmap.Config.RGB_565)// 防止内存溢出的，图片太多就这这个。还有其他设置
                        .build();

        ImageLoaderConfiguration config =
                new ImageLoaderConfiguration.Builder(context)
                        // 缓存在内存的图片的宽和高度
//                      .memoryCacheExtraOptions(480, 800)
                        .threadPriority(Thread.NORM_PRIORITY - 3)
                        .threadPoolSize(3)
                                // 配置软引用
                        .memoryCache(new WeakMemoryCache())
                        .memoryCacheSize(cacheSize)
                                // 缓存到内存的最大数据BaseBean.java
                        .discCacheSize(50 * 1024 * 1024)
                        . // 缓存到文件的最大数据
                                discCacheFileCount(500)
                                // 文件数量
                        .tasksProcessingOrder(QueueProcessingType.LIFO)
                        .discCacheFileNameGenerator(new Md5FileNameGenerator())
                        .defaultDisplayImageOptions(options)
                                // 上面的options对象，一些属性配置
                        .discCache(new UnlimitedDiscCache(cacheDir)).writeDebugLogs().build();

        ImageLoader.getInstance().init(config); // 全局初始化设置

    }

    public void init(){
        //设置该CrashHandler为程序的默认处理器
        UnCeHandler catchExcep = new UnCeHandler(this);
        Thread.setDefaultUncaughtExceptionHandler(catchExcep);
    }

    /**
     * Activity关闭时，删除Activity列表中的Activity对象*/
    public void removeActivity(Activity a){
        list.remove(a);
    }
    /**
     * Activity关闭时，删除Activity列表中的Activity对象*/
    public void removeActivitytwo(){
        for (Activity activity : listtwo) {
            if (null != activity) {
                activity.finish();
            }
        }
    }

    /**
     * 向Activity列表中添加Activity对象*/
    public void addActivity(Activity a){
        list.add(a);
    }
    /**
     * 向Activity列表中添加Activity对象*/
    public void addActivitytwo(Activity a){
        listtwo.add(a);
    }

    /**
     * 关闭Activity列表中的所有Activity*/
    public void finishActivity(){
        for (Activity activity : list) {
            if (null != activity) {
                activity.finish();
            }
        }
        //杀死该应用进程
        android.os.Process.killProcess(android.os.Process.myPid());
    }
    //关闭activity
    public void finishActivitys(){
        for (Activity activity : list) {
            if (null != activity) {
                activity.finish();
            }
        }
    }

}
